package com.qding.park.adapter.bsg.adapter.impl;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.qding.park.adapter.bsg.adapter.config.BSGConfig;
import com.qding.park.adapter.bsg.adapter.constant.ConstantFunction;
import com.qding.park.adapter.bsg.adapter.entity.ResponseMsg;
import com.qding.park.adapter.bsg.adapter.enums.ErrorCodeEnum;
import com.qding.park.adapter.bsg.adapter.util.ResponseParser;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.system.NetWorkException;
import com.qding.park.common.core.network.HttpUtil;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.common.utils.string.StrUtil;
import com.qding.park.manager.pojo.ap.ApParkTypeInfo;
import com.qding.park.manager.pojo.ap.ApSyncPageInfo;
import com.qding.park.manager.pojo.ap.ApUserCarInfo;

/**
 * @ClassName BaseDataAdapterImpl
 * @Description TODO(博思高车场基础数据接口)
 * @author LeiYang
 * @Date 2017年5月12日 下午3:29:57
 * @version 1.0.0
 */
@Component("BaseDataAdapterImpl_12")
public class BSGBaseDataAdapterImpl {
    
    private static final Logger _log = LoggerFactory.getLogger(BSGBaseDataAdapterImpl.class);
    
    public List<ApParkTypeInfo> AccountRuleByParkId(String parkCode) throws AdapterException {
        String url = BSGConfig.getAdapterUrl();
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("clientID", parkCode);
        Map<String, String> params = new HashMap<String, String>();
        params.put("UserID", "110");
        params.put("RequestFun", ConstantFunction.Parking_ParkType);
        params.put("RequestData", jsonObj.toJSONString());
        params.put("Sign", "ddd");
        try {
            _log.info("adapter request:"+params);
            String result = HttpUtil.doPost(url, params);
            _log.info("adapter response:"+result);
            java.io.Reader in = new StringReader(result);
            Document doc=doc = (new SAXBuilder()).build(in);

            String temp = doc.getRootElement().getValue();
            in.close();
            ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
            String errorCode = repmsg.getErrorCode();
            JSONObject data=(JSONObject) repmsg.getResult();
            if (!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)) {
                throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                        ExceptionMessage.createExceptionMessage(
                                AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), repmsg.getErrorMsg(),
                                ConstantFunction.Parking_ParkType + " adpater处理出错: "+repmsg.getErrorMsg()+",parkCode="+parkCode));
            }
            String text=data.getString("data");
            List<ApParkTypeInfo> resultInfos=ResponseParser.parking_parkType_parser(text);
            return resultInfos;
        } catch (AdapterException e) {
            throw e;
        }  catch (Exception e) {
            throw new RuntimeException(e);
        }
        
    }
    
    
    /**
     * @Description (TODO分页获取车辆列表)
     * @param parkCode
     * @param sync_ID
     * @return
     * @throws AdapterException
     * @throws NetWorkException
     */
    public ApSyncPageInfo listUserCar(String parkCode, String sync_ID) throws AdapterException, NetWorkException {

        String url = BSGConfig.getAdapterUrl();
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("clientID", parkCode);
        jsonObj.put("sync_ID", sync_ID);
        Map<String, String> params = new HashMap<String, String>();
        params.put("UserID", "110");
        params.put("RequestFun", ConstantFunction.Parking_SyncMember);
        params.put("RequestData", jsonObj.toJSONString());
        params.put("Sign", "ddd");
        _log.info("RequestData:" + jsonObj.toJSONString());
        try {
            _log.info("adapter request:" + params);
            String result = HttpUtil.doPost(url, params);
            _log.info("adapter response:" + StrUtil.decodeUnicode(result));
            java.io.Reader in = new StringReader(result);
            Document doc = doc = (new SAXBuilder()).build(in);

            String temp = doc.getRootElement().getValue();
            in.close();
            ResponseMsg repmsg = JSONObject.parseObject(temp, ResponseMsg.class);
            JSONObject data = (JSONObject) repmsg.getResult();
            String errorCode = repmsg.getErrorCode();
            if (!ErrorCodeEnum.SUCCESS.getCode().equals(errorCode)) {
                throw new AdapterException(AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getId(), null,
                        ExceptionMessage.createExceptionMessage(
                                AdapterException.TypeEnum.EXCEPTION_ADAPTER_FAIL.getDesc(), repmsg.getErrorMsg(),
                                ConstantFunction.Parking_SyncMember + " adpater处理出错: " + repmsg.getErrorMsg()
                                        + ",parkCode=" + parkCode + ",sync_ID=" + sync_ID));
            }
            ApSyncPageInfo pageInfo = ResponseParser.parking_SyncMember(data.getString("data"));

            return pageInfo;
        } catch (AdapterException e) {
            throw e;
        } catch (NetWorkException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    /**
     * @Description (TODO获取所有车辆列表)
     * @param parkCode
     * @return
     * @throws AdapterException
     * @throws NetWorkException
     */
    public List<ApUserCarInfo> allUserCar(String parkCode) throws AdapterException, NetWorkException {
        List<ApUserCarInfo> usercarList = new ArrayList<ApUserCarInfo>();
        ApSyncPageInfo page = listUserCar(parkCode, "-1");// 查询第一页
        List list = page.getPageData();
        if (!ListUtil.isEmpty(list)) {
            usercarList.addAll(list);
        }

        while (page.getSync_Count() > 0) {
            // 查询下一页
            page = listUserCar(parkCode, page.getSync_ID());
            if (!ListUtil.isEmpty(page.getPageData())) {
                usercarList.addAll(page.getPageData());
            }
        }

        return usercarList;
    }

}
